/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ces31.ChineseDicesServer.RN;

import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import ces31.ChineseDicesCommon.ClienteInterface;
import java.rmi.Naming;

/**
 *
 * @author Imada
 */
public class RN_SalaDeEspera {

    private RN_SalaDeEspera() {
    }

    /**
     * Singleton
     * @return singleton instance of waiting room
     */
    public static RN_SalaDeEspera instanciaDe() {
        return salaDeEspera;
    }

    public void conectarJogador(String IPUser, String name) {
         System.out.println("Conectando Usuario...");
        try {
            System.out.println("//" + IPUser + ":" +
                               ClienteInterface.port + "/" + ClienteInterface.bindname);
            ClienteInterface client = (ClienteInterface) Naming.lookup("rmi://" + IPUser + ":" +
                               ClienteInterface.port + "/" + ClienteInterface.bindname);

            System.out.println("Conectado!");
            colocarJogadorNaSalaDeEspera(name,client);

		} catch (Exception e) {
			System.out.println("Erro na conexao do cliente");
			e.printStackTrace();
		}
    }

    /**
     * -> Put in List <tt>clientsWaiting</tt>
     * -> Collaboration:
     * [VF1]sendMessage
     *
     * @param client who will enter waitingRoom
     * @return true when there are enough player to start the game.
     */
    public void colocarJogadorNaSalaDeEspera(String name, ClienteInterface client) throws RemoteException{
        if (getUsuariosEsperando().size() == 0) {
            getUsuariosEsperando().put(name, client);
            apresentarMensagem("Espera Adversario",client);
        } else if (getUsuariosEsperando().size() == 1) {
            getUsuariosEsperando().put(name, client);
            apresentarMensagem("Espera Adversario",client);
            iniciarJogo();
        }
        else {
            apresentarMensagem("Sala Cheia",client);
        }
        return;
    }

    public void apresentarMensagem(String mensagem, ClienteInterface client) throws RemoteException{
        client.entregarMensagem(mensagem);
    }

    /**
     * -> Remove from List clientsWaiting
     *
     * @param name of the player.
     */
    public void desconectarJogador(String name) {
        removerJogadorSalaEspera(name);
    }

    private void removerJogadorSalaEspera(String name){
        getUsuariosEsperando().remove(name);
    }
    /**
     * -> Collaborations:
     * new Player
     * new Game
     *
     * @return Game instance with the players.
     */
    public void iniciarJogo() {
        List<RN_Jogador> players = new LinkedList<RN_Jogador>();

        Iterator<String> keysIterator = getUsuariosEsperando().keySet().iterator();
        while (keysIterator.hasNext()) {
            String key = keysIterator.next();
            System.out.println("Adicionado ao jogo: "+key);
//        for(String key : (Set<String>)getUsuariosEsperando().keySet()){
            players.add(new RN_Jogador(getUsuariosEsperando().get(key), key));
        }
        setJogo(new RN_Jogo(players));
        getJogo().inicializarJogadores();
    }

    public RN_Jogo getJogo() {
        return esseJogo;
    }

    public void setJogo(RN_Jogo thisgame) {
        this.esseJogo = thisgame;
    }

    public Map<String, ClienteInterface> getUsuariosEsperando() {
        return usuariosEsperando;
    }
    private Map<String, ClienteInterface> usuariosEsperando = new HashMap<String, ClienteInterface>();
    private static RN_SalaDeEspera salaDeEspera = new RN_SalaDeEspera();
    private RN_Jogo esseJogo;
}